package com.joejag.mavenstats.server.reports;

import com.joejag.mavenstats.client.dto.DependencyDTO;
import com.joejag.mavenstats.client.dto.ProjectDTO;
import com.joejag.mavenstats.server.dao.ProjectsDao;
import com.joejag.mavenstats.server.xml.MavenProjectReader;

import java.util.Map;
import java.util.TreeMap;

public class CommonReportUtils
{
  private enum ByVariable
  {
    GROUPING, NAME;
  }

  public static Map<String, Integer> getOccurancesMapOfDependenciesByGrouping(ProjectsDao projectsDao)
  {
    return doWork(projectsDao, ByVariable.GROUPING);
  }

  public static Map<String, Integer> getOccurancesMapOfDependenciesByName(ProjectsDao projectsDao)
  {
    return doWork(projectsDao, ByVariable.NAME);
  }

  public static Map<String, Integer> doWork(ProjectsDao projectsDao, ByVariable byVar)
  {
    Map<String, Integer> result = new TreeMap<String, Integer>();
    for (String teamName : projectsDao.getTeamNames())
      for (ProjectDTO dto : projectsDao.getTeamProjects(teamName))
        for (DependencyDTO dependencyDTO : new MavenProjectReader(dto.projectURL).getDependencies())
          if (result.containsKey(getVar(dependencyDTO, byVar)))
          {
            int count = result.get(dependencyDTO.grouping);
            result.put(dependencyDTO.grouping, ++count);
          } else
            result.put(dependencyDTO.grouping, 1);
    return result;
  }

  private static String getVar(DependencyDTO dependencyDTO, ByVariable byVar)
  {
    if (byVar.equals(ByVariable.GROUPING))
      return dependencyDTO.grouping;

    if (byVar.equals(ByVariable.NAME))
      return dependencyDTO.name;

    throw new IllegalStateException();
  }
}
